package com.ezgo.erc.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ezgo.erc.entity.Sysuser;
import com.ezgo.erc.master.utils.CookieUtil;
import com.ezgo.erc.master.utils.MD5Util;
import com.ezgo.erc.master.utils.StringUtil;
import com.ezgo.erc.service.CacheService;
import com.ezgo.erc.servlet.ValidateCodeServlet;
import com.ezgo.erc.utils.UserUtil;
import com.google.common.collect.Maps;

/**
 * 
 * (系统登录)模块 TODO(登录视图控制层)
 * 
 * @author devintam
 * @date 2015年7月29日 下午4:09:15
 *
 */
@Controller
@SessionAttributes(types = Sysuser.class, value = UserUtil.CACHE_USER)
public class LoginController extends BaseController {

	private static CacheService cache = UserUtil.cacheService;
	private Map<String, Object> map = Maps.newHashMap();

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		Sysuser user = UserUtil.getUser();
		if (user != null)
			return "redirect:index";
		request.setAttribute("message", "成功");
		return "sys/sysLogin";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		map.clear();
		String userName = getParam(request, "username");
		map.put("userName", userName);
		map.put("password", MD5Util.md5(getParam(request, "password")));
		Sysuser user = UserUtil.getUser(map);
		if (user != null) {
			return "redirect:index";
		}
		if (isValidateCodeLogin(userName, false, false)) {
			// 判断验证码
			HttpSession session = request.getSession();
			String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
			if (getParam(request, "code").toUpperCase().equals(code)) {
				model.addAttribute("message", "验证码错误.");
			}
		} else {
			model.addAttribute("message", "用户名或密码错误");
		}
		model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(userName, true, false));
		return "sys/sysLogin";
	}

	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtil.isNotBlank(theme)) {
			CookieUtil.setCookie(response, "theme", theme);
		} else {
			theme = CookieUtil.getCookie(request, "theme");
		}
		return "redirect:" + request.getParameter("url");
	}

	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		Sysuser user = UserUtil.getUser();
		if (user == null)
			return "redirect:login";

		isValidateCodeLogin(user.getUserName(), false, true);
		cache.set("siteId", StringUtil.toLong(CookieUtil.getCookie(request, "siteId")) + "", 7200);
		return "sys/sysIndex";
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		Sysuser user = UserUtil.getUser();
		if (user != null)
			UserUtil.calcLoginFail(user.getUserName(), 0, false);
		UserUtil.userLogout();
		return "redirect:login";
	}

	/**
	 * 是否是验证码登录
	 * 
	 * @param useruame
	 *            用户名
	 * @param isFail
	 *            计数加1
	 * @param clean
	 *            计数清零
	 * @return
	 */
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean) {
		Map<String, Integer> loginFailMap = null;
		if (cache.exists("loginFailMap")) {
			loginFailMap = JSONObject.parseObject(cache.get("loginFailMap"), new TypeReference<Map<String, Integer>>() {
			});
			cache.del("loginFailMap");
		} else {
			loginFailMap = Maps.newHashMap();
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum == null) {
			loginFailNum = 0;
		}
		if (isFail) {
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean) {
			loginFailMap.remove(useruame);
		}
		cache.set("loginFailMap", JSONObject.toJSONString(loginFailMap));
		return loginFailNum >= 3;
	}

}
